package vn.personal.anhht.bloback12.activity;

import java.util.ArrayList;
import java.util.List;

import vn.personal.anhht.bloback12.database.CallBlockDatabaseFilterAdapter;
import vn.personal.anhht.bloback12.util.LocalizationUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;



public class FilterActivity extends Activity{

	private CallBlockDatabaseFilterAdapter databaseFilterAdapter;
	private ListView lvFilter;
	private ArrayAdapter<String> listAdapter;
	private List<String> listWords = new ArrayList<String>();
	private Button btnAdd;
	private EditText etFilter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		LocalizationUtil.setupLanguage(getApplicationContext());
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_filter);
		this.setTitle(getResources().getString(R.string.title_filter));
		initFilter();
		filterListen();	
		
	}
	
	private void initFilter(){
		databaseFilterAdapter = new CallBlockDatabaseFilterAdapter(getApplicationContext());
		etFilter = (EditText) findViewById(R.id.et_filter);
		btnAdd = (Button) findViewById(R.id.btn_filter_add);
		lvFilter = (ListView) findViewById(R.id.lv_filter);
		listAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, listWords);
		//dialog =  new ProgressDialog(this);
		refresh();
	}
	
	private void filterListen(){
		etFilter.setOnKeyListener(new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				
				if((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)){
					//save keyword to filters table
					addFilter();
					return true;
				}
				return false;
			}
		});
		btnAdd.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				addFilter();
			}
		});
		lvFilter.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				
				displayDialog(position);
			}
			
		});
		
	}
	
	public void addFilter(){
		
		String word = etFilter.getText().toString().trim();
		if(!"".equals(word)){
			databaseFilterAdapter.open();
			if(databaseFilterAdapter.isWordExist(word)){
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.toast_filter_exist), Toast.LENGTH_LONG).show();
				databaseFilterAdapter.close();
			}else{
				
				databaseFilterAdapter.addFilter(word);
				databaseFilterAdapter.close();
				refresh();
			}
			etFilter.setText("");
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mn_filter, menu);
		return true;
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		
		switch(item.getItemId()){
			case R.id.item_filter_back:{
				back(RESULT_OK);
				break;
			}
			case R.id.item_filter_clear:{
			    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
	            alert.setTitle(getResources().getString(R.string.history_alert_title));
	            alert.setMessage(getResources().getString(R.string.history_alert_msg));
	            alert.setPositiveButton(getResources().getString(R.string.ok) , new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int whichButton) {
	                    databaseFilterAdapter.open();
	                    databaseFilterAdapter.deleteAll();
	                    databaseFilterAdapter.close();
	                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.history_toast_delok),
	                            Toast.LENGTH_LONG).show();
	                    refresh();
	                }
	            });

	            alert.setNegativeButton(getResources().getString(R.string.cancel),
	                    new DialogInterface.OnClickListener() {
	                        public void onClick(DialogInterface dialog, int whichButton) {
	                            dialog.cancel();
	                        }
	                    });
	            alert.show();
	            break;
			}
			default:super.onOptionsItemSelected(item); 
		}
		return true;
	}

	public void displayDialog(final int position){
		final String word = listWords.get(position);
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(getResources().getString(R.string.ft_alert_title));
		alert.setMessage(getResources().getString(R.string.ft_alert_message) + " : " + word);;
		alert.setPositiveButton(getResources().getString(R.string.ft_alert_btremove) , new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				databaseFilterAdapter.open();
				databaseFilterAdapter.deleteFilterByWord(word);
				databaseFilterAdapter.close();
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.ft_toast_remove),
						Toast.LENGTH_LONG).show();
				refresh();
			}
		});

		alert.setNegativeButton(getResources().getString(R.string.cancel),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		alert.show();
	}
	
	public void refresh(){
		listWords.clear();
		loadWords();
		lvFilter.setAdapter(listAdapter);
	}
	
	private void loadWords(){
		
		databaseFilterAdapter.open();
		Cursor cr = databaseFilterAdapter.selectAllWords();
		if(cr.moveToFirst()){
			int index = cr.getColumnIndex(CallBlockDatabaseFilterAdapter.KEY_WORD);
			do{
				listWords.add(cr.getString(index));
			}while(cr.moveToNext());
		}
		cr.close();
		databaseFilterAdapter.close();
	}
	/*
	 * TyHH: return previous activity
	 */
	public void back(int resultCode) {

		Intent replyIntent = new Intent();
		setResult(resultCode, replyIntent);
		finish();
	}
	
}
